package cc.zy.base.hr.controller;

import cc.zy.base.common.annotation.ControllerEndpoint;
import cc.zy.base.common.controller.BaseController;
import cc.zy.base.common.entity.FebsConstant;
import cc.zy.base.common.entity.FebsResponse;
import cc.zy.base.common.entity.QueryRequest;
import cc.zy.base.common.exception.FebsException;
import cc.zy.base.common.utils.DateUtil;
import cc.zy.base.common.utils.FebsUtil;
import cc.zy.base.hr.entity.*;
import cc.zy.base.hr.service.IExecuteAdjustLogService;
import cc.zy.base.hr.service.IExecuteScheduleService;
import cc.zy.base.hr.service.IExecuteService;
import com.wuwenze.poi.ExcelKit;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 培训执行计划 控制器
 * @author
 * @time 2022/03/05 10:32:24
 */
@Controller
@Slf4j
@Validated
@RequiredArgsConstructor
public class ExecuteScheduleController extends BaseController {

    private final IExecuteScheduleService executeScheduleService;

    private final IExecuteService executeService;

    private final IExecuteAdjustLogService logService;



    /**
     * @author yanxingtong
     * 弹出执行计划更新模态框
     * @param id
     * @param model
     * @return
     */
    @GetMapping(FebsConstant.VIEW_PREFIX + "executeSchedule/update/{id}")
    public String executeScheduleUpdate(@PathVariable Integer id, Model model) {
        resolveExecuteScheduleModel(id, model, false);
        return FebsUtil.hrView("plan/execute/executeScheduleUpdate");
    }

    private void resolveExecuteScheduleModel(Integer id, Model model, Boolean transform) {
        ExecuteSchedule executeSchedule = executeScheduleService.findById(id);
        if (executeSchedule.getPlanDate() != null) {
            model.addAttribute("planDate", DateUtil.getDateFormat(executeSchedule.getPlanDate(), DateUtil.FULL_TIME_SPLIT_PATTERN));
        }
        model.addAttribute("executeSchedule", executeSchedule);
    }



    /**
     * 查找标签
     * @param request
     * @param executeSchedule
     * @return
     */
    @GetMapping("executeSchedule/list")
    @ResponseBody
    public FebsResponse executeScheduleList(QueryRequest request, ExecuteSchedule executeSchedule) {

        log.debug("前台传来的对象是 before：" + executeSchedule);

        Map<String, Object> dataTable = getDataTable(executeScheduleService.findExecuteScheduleByPage(request, executeSchedule));
        return new FebsResponse().success().data(dataTable);
    }


    /**
     * 删除标签
     * @param executeScheduleId
     * @return
     */
    @GetMapping("executeSchedule/delete/{executeScheduleId}")
    @ControllerEndpoint(operation = "删除计划", exceptionMessage = "删除计划异常")
    @ResponseBody
    public FebsResponse deleteExecuteSchedules(@NotBlank(message = "{required}") @PathVariable String executeScheduleId) {

        executeScheduleService.deleteExecuteSchedule(Integer.valueOf(executeScheduleId));
        return new FebsResponse().success();
    }
    /**
     * 查询所有课程courseName
     * @return
     */
    @GetMapping("executeSchedule/courseName")
    public FebsResponse queryCourseName() {

        List<Course> courseNames = executeScheduleService.queryCourseName();
        return new FebsResponse().success().data(courseNames);
    }

    /**
     * 修改计划
     * @param executeSchedule
     * @return
     */
    @PostMapping("executeSchedule/update")
    @ControllerEndpoint(operation = "修改计划", exceptionMessage = "修改计划信息异常")
    @ResponseBody
    public FebsResponse updateExecuteSchedule(@Valid ExecuteSchedule executeSchedule) {
        log.debug("修改标签id：" + executeSchedule.getId());

        if (executeSchedule == null) {
            throw new FebsException("标签ID为空");
        }

        int executeId = executeSchedule.getTrainningPlanExecuteId();

        //依靠id查询出旧值，在考新值给log表
        Execute oldDataExec = executeService.getById(executeId);
        ExecuteSchedule oldDataES = executeScheduleService.getById(executeSchedule.getId());

        //date转换格式
        String afterUpdatedFormatPlanDate = DateUtil.getDateFormat(executeSchedule.getPlanDate(), "yyyy-MM-dd");
        String beforeUpdatedFormatPlanDate = DateUtil.getDateFormat(oldDataES.getPlanDate(), "yyyy-MM-dd");

        ExecuteAdjustLog adjustLog = new ExecuteAdjustLog();
        if(!oldDataExec.getTeacherInfo().equals(executeSchedule.getTeacherInfo()) & !oldDataES.getPlanDate().equals(executeSchedule.getPlanDate())){
            adjustLog.setAdjustType(12);
            adjustLog.setOriginalValue("原讲师:" + oldDataExec.getTeacherInfo() + "---" + "原执行时间:" + beforeUpdatedFormatPlanDate);
            adjustLog.setCreateDate(new Date());
            adjustLog.setCreateUserId(FebsUtil.getCurrentUser().getUserId());
            adjustLog.setAdjustValue("调整后老师" + executeSchedule.getTeacherInfo() + "---" + "调整后执行时间:" + afterUpdatedFormatPlanDate);
            adjustLog.setRemark(executeSchedule.getRemark());
            //入库~~~
            logService.saveExecuteAdjustLog(adjustLog);
        }
        else if(!oldDataExec.getTeacherInfo().equals(executeSchedule.getTeacherInfo()) & oldDataES.getPlanDate().equals(executeSchedule.getPlanDate())){
            adjustLog.setAdjustType(1);
            adjustLog.setOriginalValue("原讲师:" + oldDataExec.getTeacherInfo());
            adjustLog.setCreateDate(new Date());
            adjustLog.setCreateUserId(FebsUtil.getCurrentUser().getUserId());
            adjustLog.setAdjustValue("调整后讲师" + executeSchedule.getTeacherInfo());
            adjustLog.setRemark(executeSchedule.getRemark());
            //入库~~~
            logService.saveExecuteAdjustLog(adjustLog);
        }
        else if(oldDataExec.getTeacherInfo().equals(executeSchedule.getTeacherInfo()) & !oldDataES.getPlanDate().equals(executeSchedule.getPlanDate())){
            adjustLog.setAdjustType(2);
            adjustLog.setOriginalValue("原执行时间:" + beforeUpdatedFormatPlanDate);
            adjustLog.setCreateDate(new Date());
            adjustLog.setCreateUserId(FebsUtil.getCurrentUser().getUserId());
            adjustLog.setAdjustValue("调整后执行时间:" + afterUpdatedFormatPlanDate);
            adjustLog.setRemark(executeSchedule.getRemark());
            //入库~~~
            logService.saveExecuteAdjustLog(adjustLog);
        }else{
            new FebsResponse().fail().message("输入的日期和讲师信息无变化，计划未做修改");
        }

        //修改定表的lastModifyUserId, TeacherInfo
        Execute execute = new Execute();
        Long userId = FebsUtil.getCurrentUser().getUserId();
        execute.setLastModifyUserId(userId);
        execute.setId(executeId);
        execute.setTeacherInfo(executeSchedule.getTeacherInfo());
        executeService.updateExecute(execute);

        //修改executeSchedule中的PlanDate
        executeScheduleService.updatePlanDate(executeSchedule);

        return new FebsResponse().success();
    }

    /**
     * 导出excel
     * @param response
     * @param executeSchedule
     */
    @GetMapping("executeSchedule/excel")
    @ControllerEndpoint(exceptionMessage = "导出Excel异常")
    public void export(HttpServletResponse response, ExecuteSchedule executeSchedule) {

        log.debug(String.format("response = %s", response));
        log.debug(String.format("tag = %s", executeSchedule));

        List<ExecuteSchedule> executeSchedules = executeScheduleService.findExecuteScheduleListNotPage(executeSchedule);
        ExcelKit.$Export(ExecuteSchedule.class, response).downXlsx(executeSchedules, false);
    }


}
